package com.istudy.uniplugin.camera;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;

import com.google.android.cameraview.CameraView;

import java.io.ByteArrayOutputStream;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

/**
 * @author bobxie
 */
public class MainActivity extends FragmentActivity implements EasyPermissions.PermissionCallbacks, View.OnClickListener {
    private static final String TAG = "MainActivity";
    CameraView cameraView;
    ImageView imageViewResult;
    ImageView imageViewResult1;
    Button btnTakePicture;
    Button btnBack;

    private boolean isStop;

    private boolean isCaptureImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //取消标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //取消状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        cameraView = findViewById(R.id.cameraView);
        imageViewResult = findViewById(R.id.imageViewResult);
        imageViewResult1 = findViewById(R.id.imageViewResult1);
        btnTakePicture = findViewById(R.id.btnTakePicture);
        btnBack = findViewById(R.id.btnBack);

        btnBack.setOnClickListener(this);
        btnTakePicture.setOnClickListener(this);


        //这里后续可以改成参数传输 动态设置
        cameraView.setFacing(CameraView.FACING_FRONT);

        cameraView.setAutoFocus(true);
        if (cameraView != null) {
            cameraView.addCallback(mCallback);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stop();
    }

    private void start() {
        methodRequiresTwoPermission();
    }

    private void stop() {
        isStop = true;
        cameraView.stop();
    }

    private void methodRequiresTwoPermission() {
        String[] perms = {Manifest.permission.CAMERA};
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED) {
            Log.d(TAG, "同意权限了");
            cameraView.start();
            isStop = false;
        } else {
            EasyPermissions.requestPermissions(this, "申请必要的权限",
                    0, perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> list) {
        // Some permissions have been granted
        Log.d(TAG, "onPermissionsGranted===" + list);
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> list) {
        // Some permissions have been denied
        Log.d(TAG, "onPermissionsDenied===" + list);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnBack:
                onBackPressed();
                break;
            case R.id.btnTakePicture:
                if (!isCaptureImage) {
                    isCaptureImage = true;
                    if (isStop) {
                        start();
                    }
                    cameraView.takePicture();
                }
                break;
            default:
                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != cameraView) {
            cameraView = null;
        }
    }


    private CameraView.Callback mCallback = new CameraView.Callback() {

        @Override
        public void onCameraOpened(CameraView cameraView) {
            Log.d(TAG, "onCameraOpened");
        }

        @Override
        public void onCameraClosed(CameraView cameraView) {
            Log.d(TAG, "onCameraClosed");
        }

        @Override
        public void onPictureTaken(CameraView cameraView, final byte[] pic) {
            Log.d(TAG, "onPictureTaken " + pic.length);
            isCaptureImage = false;
            Bitmap cameraBitmap = BitmapFactory.decodeByteArray(pic, 0, pic.length);
            // use matrix to reverse image data and keep it normal
            Matrix mtx = new Matrix();
            //this will prevent mirror effect
            mtx.preScale(-1.0f, 1.0f);
            // Rotating Bitmap , create real image that we want
            Bitmap newImage = Bitmap.createBitmap(cameraBitmap, 0, 0, cameraBitmap.getWidth(), cameraBitmap.getHeight(), mtx, true);

            Log.d(TAG, "newImage size " + newImage.getWidth() + "x" + newImage.getHeight());
            //旋转后的图片  只用于显示
            imageViewResult1.setImageBitmap(newImage);
            //TODO   这里就要回调给uni-app
            byte[] result = bitmap2Bytes(newImage);

        }
    };

    public byte[] bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 90, baos);
        return baos.toByteArray();
    }
}
